package org.lyq.erp.auth.employee.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.lyq.erp.auth.department.pojo.Department;
import org.lyq.erp.auth.department.service.DepartmentService;
import org.lyq.erp.auth.employee.pojo.Employee;
import org.lyq.erp.auth.employee.service.EmployeeService;
import org.lyq.erp.auth.role.pojo.Role;
import org.lyq.erp.auth.role.service.RoleService;
import org.lyq.erp.config.exception.myexception.MyException;
import org.lyq.erp.config.json.JSONResult;
import org.lyq.erp.utils.excel.ExcelUtil;
import org.lyq.erp.utils.string.ObjectEmptyUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 
 * @ClassName: EmployeeController
 * @Description: 员工模块的控制层
 * @author LYQ(廖先生)
 * @date 2017年12月15日 下午10:18:33
 *
 */
@Controller
@RequestMapping("/employee")
public class EmployeeController {

	@Resource
	private EmployeeService employeeService;
	@Resource
	private DepartmentService departmentService;
	@Resource
	private RoleService roleService;

	/**
	 * 查询所有的员工信息
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping("/list")
	public String list(ModelMap map, Employee employee) {

		// 查询所有员工信息并且返回出去
		List<Department> dList = departmentService.list();
		map.addAttribute("dList", dList);

		// 查询所有员工信息并且返回出去
		List<Employee> eList = employeeService.selectAllEmployee(employee);
		map.addAttribute("eList", eList);

		// 查询所有角色信息并且返回出去
		List<Role> rList = roleService.selectAllRole();
		map.addAttribute("rList", rList);

		return "employee_list";
	}

	/**
	 * 验证用户名是否存在
	 * 
	 * @param empUsername
	 * @return
	 */
	@RequestMapping(value = "/checkName", produces = "application/json;charset=UTF-8")
	public @ResponseBody String checkNameValid(@RequestParam String empUsername) {
		if (empUsername != null && empUsername.trim().length() > 0) {

			boolean result = true;
			boolean falg = employeeService.checkName(empUsername);
			result = falg;
			Map<String, Boolean> map = new HashMap<>();
			map.put("valid", result);
			ObjectMapper mapper = new ObjectMapper();
			String resultString = "";
			try {
				resultString = mapper.writeValueAsString(map);
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
			return resultString;
		} else {
			throw new MyException("验证失败");
		}
	}

	/**
	 * 控制插入或者控制修改一条员工信息
	 * 
	 * @return
	 */
	@RequestMapping("/insertAndUpdate")
	public String insertAndUpdate(Employee employee, Integer menuUuid, Integer empUuid, Integer[] roleUuids,
			HttpServletRequest request) {

		if (empUuid == null) {

			try {
				employeeService.insert(employee, roleUuids);
			} catch (Exception e) {
				throw new MyException("添加员工失败");
			}
			return "redirect:/employee/list?menuUuid=" + menuUuid;

		} else {

			try {
				employeeService.update(employee, empUuid, roleUuids);
			} catch (Exception e) {
				throw new MyException("修改员工失败");
			}

			return "redirect:/employee/list?menuUuid=" + menuUuid;
		}
	}

	/**
	 * 查询一条用户信息
	 * 
	 * @param empUuid
	 * @return
	 */
	@RequestMapping("/getEmployee")
	@ResponseBody
	public Employee getEmployee(Integer empUuid) {
		if (empUuid != null) {
			Employee emp = employeeService.selectByPrimaryKey(empUuid);
			return emp;
		} else {
			throw new MyException("查询员工失败，员工id不能为空！！");
		}

	}

	/**
	 * 删除一条员工数据
	 * 
	 * @param empUuid
	 * @return
	 */
	@RequestMapping("/delete")
	public String delete(Integer empUuid, Integer menuUuid) {

		if (empUuid != null) {
			try {
				employeeService.delete(empUuid);
			} catch (Exception e) {
				throw new MyException("删除员工失败");
			}
		} else {
			throw new MyException("删除员工失败，员工id不为空");
		}
		return "redirect:/employee/list?menuUuid=" + menuUuid;
	}

	/**
	 * 获取用户名
	 * 
	 * @param empIdcard
	 * @param empName
	 * @param out
	 * @throws IOException
	 */
	@RequestMapping("/getUsername")
	@ResponseBody
	public JSONResult getUsername(Employee emp) throws IOException {

		if (!ObjectEmptyUtils.isNotEmpty(emp) || ObjectEmptyUtils.isEmptyString(emp.getEmpName())
				|| ObjectEmptyUtils.isEmptyString(emp.getEmpIdcard())) {
			return JSONResult.errorMsg("employee002");
		} else {
			emp = employeeService.getEmpUsernameByEmpNameAndEmpIdcard(emp);
			if (emp == null) {
				return JSONResult.errorMsg("employee002");
			} else if (emp != null && emp.getStatus() != null && emp.getStatus() == 1) {
				return JSONResult.ok(emp.getEmpUsername());
			} else {
				return JSONResult.errorMsg("employee001");
			}

		}

	}

	/**
	 * 验证手机号是否绑定
	 * 
	 * @param empTele
	 * @return
	 */
	@RequestMapping(value = "/checkTele", produces = "application/json;charset=UTF-8")
	public @ResponseBody String checkTeleValid(@RequestParam String empTele) {

		if (empTele != null) {

			boolean result = true;
			boolean falg = employeeService.checkTele(empTele);
			result = falg;
			Map<String, Boolean> map = new HashMap<>();
			map.put("valid", result);
			ObjectMapper mapper = new ObjectMapper();
			String resultString = "";
			try {
				resultString = mapper.writeValueAsString(map);
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
			return resultString;
		} else {
			throw new MyException("验证失败");
		}

	}

	/**
	 * 根据条件下载员工信息的excel表
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/downloadEmployeeExcel")
	public void download(HttpServletRequest request, HttpServletResponse response, String template, Employee employee)
			throws Exception {

		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/vnd.ms-excel");

		String xlsName = "员工数据表.xls";

		// 下载文件的默认名称
		response.setHeader("Content-Disposition",
				"attachment;filename=" + new String(xlsName.getBytes("utf-8"), "iso8859-1"));
		// 编码
		response.setCharacterEncoding("UTF-8");

		List<Employee> list = new ArrayList<Employee>();
		if (template == null) {
			list = employeeService.selectAllEmployee(employee);
			Map<String, String> map = new HashMap<String, String>();
			map.put("title", "员工信息详细表");
			map.put("total", list.size() + " 条");
			map.put("date", getDate());
			ExcelUtil.getInstance().exportObj2ExcelByTemplate(map, "web-info-template.xls", response.getOutputStream(),
					list, Employee.class, true);
		}
		Map<String, String> map = new HashMap<String, String>();
		map.put("title", "员工信息模板表");

		ExcelUtil.getInstance().exportObj2ExcelByTemplate(map, "web-info-template1.xls", response.getOutputStream(),
				list, Employee.class, true);

	}

	private String getDate() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
		return sdf.format(new Date());
	}

}
